package com.example.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.modal.CardInfo;
import com.example.modal.ExamineItem;
import com.example.modal.MostPortItem;
import com.example.modal.MultimediaDemand;
import com.example.modal.MultimediaRecord;
import com.example.modal.QcCard;
import com.example.modal.User;
import com.example.modal.WorkingProcedure;
import com.example.qcweb.DateManager;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;


public class DBDao {
    private static DBOpenHelper helper;
    private static SQLiteDatabase db;

    //实体类模型数据库
    public DBDao(Context context) {

        helper = new DBOpenHelper(context);
        // TODO Auto-generated constructor stub
    }

    public void addUser(User user) {
        db = helper.getReadableDatabase();
        //db.execSQL("insert into");
    }

    public List<CardInfo> findAllCardInfo() {
        List<CardInfo> listcard = new ArrayList<CardInfo>();
        db = helper.getReadableDatabase();
        Cursor cursor = db.query("CardInfo", new String[]{"FileName", "ModificationDate", "KEYCardCode", " DrawingNumber", " ProductName", "ProductModel", "ProductBatchNumber", "QcCardId"}, null, null, null, null, null, null);
        while (cursor.moveToNext()) {
            listcard.add(new CardInfo(cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7)));
        }

        return listcard;

    }

    public List<WorkingProcedure> findAllWorkProcedure(String keycardcode) {
        List<WorkingProcedure> procedure = new ArrayList<WorkingProcedure>();
        db = helper.getReadableDatabase();
        String[] args = {String.valueOf(keycardcode)};
        Cursor cursor = db.query("WorkingProcedure", null, "KEYCardCode=?", args, null, null, "Produce,Step", null);
        while (cursor.moveToNext()) {
            procedure.add(new WorkingProcedure(cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7), cursor.getString(8), cursor.getString(9), cursor.getString(10), cursor.getString(11), cursor.getString(12), cursor.getString(13), cursor.getString(14), cursor.getString(15), cursor.getString(16), cursor.getString(17), cursor.getString(18), cursor.getString(19), cursor.getString(20), cursor.getString(21), cursor.getString(22), cursor.getString(23), cursor.getString(24), cursor.getString(25)));
        }

        return procedure;

    }

    public QcCard findCardById(String cardid) {
        QcCard card = null;

        db = helper.getReadableDatabase();
        Cursor cursor = db.query("QcCard", new String[]{"systemId", "channel", "createBy", "createDate", "drawingNumber", " lastModifyDate", "planAmount", " processKind", " produceAmount", "productModel", " productName", " productNumber", "cardCode", " state", " taskNumber", "technicNubmer", " templateNumber", " workshop", "processType", " cardType", " outputTable", "needForm", " mainWorkshop", " step", "materialInfo", " productBatchNumber", "nonmetalDate", " technicVerify", " attemperVerify", "lastTechnicInfo", "lastAttemperInfo", " taskRemark", "taskItemId", " kEYCardCode", " techMonitor", "shopDirector", " ration", " attemper", "manHour", " team"}, "KEYCardCode=?", new String[]{String.valueOf(cardid)}, null, null, null, null);
        while (cursor.moveToNext()) {
            card = new QcCard(cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5),
                    cursor.getString(6), cursor.getString(7), cursor.getString(8), cursor.getString(9), cursor.getString(10),
                    cursor.getString(11), cursor.getString(12), cursor.getString(13), cursor.getString(14), cursor.getString(15), cursor.getString(16), cursor.getString(17),
                    cursor.getString(18), cursor.getString(19), cursor.getString(20), cursor.getString(21),
                    cursor.getString(22), cursor.getString(23), cursor.getString(24), cursor.getString(25), cursor.getString(26),
                    cursor.getString(27), cursor.getString(28), cursor.getString(29), cursor.getString(30), cursor.getString(31), cursor.getString(32),
                    cursor.getString(33), cursor.getString(34), cursor.getString(35), cursor.getString(36), cursor.getString(37), cursor.getString(38), cursor.getString(39));
        }

        return card;

    }

    public static List<MostPortItem> findMostPortItem(String cardid, String stepid) {
        List<MostPortItem> portItems = new ArrayList<MostPortItem>();
        db = helper.getReadableDatabase();
        Cursor cursor = db.query("MostPortItem", null, "KEYCardCode=?" + "AND StepId=?", new String[]{String.valueOf(cardid), String.valueOf(stepid)}, null, null, "SequenceNumber", null);
        while (cursor.moveToNext()) {
            portItems.add(new MostPortItem(cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5),
                    cursor.getString(6), cursor.getString(7), cursor.getString(8), cursor.getString(9), cursor.getString(10),
                    cursor.getString(11), cursor.getString(12), cursor.getString(13), cursor.getString(14), cursor.getString(15), cursor.getString(16)));

        }

        return portItems;

    }

    //是否关键
    public static boolean isGj(String cardid) {
        db = helper.getReadableDatabase();
        Cursor cursor = db.query("WorkingProcedure", null, "KEYCardCode=?" + "AND LIKE(?,Character)", new String[]{String.valueOf(cardid), "%关键%"}, null, null, null, null);
        if (cursor.moveToFirst()) {
            return true;

        } else {
            return false;
        }


    }

    //是否军检
    public static boolean isJJ(String cardid) {
        db = helper.getReadableDatabase();
        Cursor cursor = db.query("WorkingProcedure", null, "KEYCardCode=?" + "AND LIKE(?,Character)", new String[]{String.valueOf(cardid), "%军检%"}, null, null, null, null);
        if (cursor.moveToFirst()) {
            return true;

        } else {
            return false;
        }


    }

    public static List<ExamineItem> findExamItems(String cardid, String stepid) {
        List<ExamineItem> examineItems = new ArrayList<ExamineItem>();
        db = helper.getReadableDatabase();
        Cursor cursor = db.query("ExamineItem", null, "KEYCardCode=?" + "AND StepId=?", new String[]{String.valueOf(cardid), String.valueOf(stepid)}, null, null, "SequenceNumber", null);
        while (cursor.moveToNext()) {
            examineItems.add(new ExamineItem(cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5),
                    cursor.getString(6), cursor.getString(7), cursor.getString(8), cursor.getString(9), cursor.getString(10),
                    cursor.getString(11), cursor.getString(12), cursor.getString(18), cursor.getString(19), cursor.getString(20), cursor.getString(21),
                    cursor.getString(22), cursor.getString(23), cursor.getString(24), cursor.getString(25), cursor.getString(26), cursor.getString(27), cursor.getString(28), cursor.getString(29), cursor.getString(30), cursor.getString(31), cursor.getString(32)));

        }

        return examineItems;

    }

    public static List<MultimediaRecord> findMultimediaRecords(String cardid, String stepid) {
        List<MultimediaRecord> multimediaRecords = new ArrayList<MultimediaRecord>();
        db = helper.getReadableDatabase();
        Cursor cursor = db.query("MultimediaRecord", null, "KEYCardCode=? and StepId=?", new String[]{String.valueOf(cardid), String.valueOf(stepid)}, null, null, null, null);
        while (cursor.moveToNext()) {
            multimediaRecords.add(new MultimediaRecord(cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5),
                    cursor.getString(6), cursor.getString(7), cursor.getString(8), cursor.getString(9), cursor.getString(10), cursor.getString(11), cursor.getString(12)));

        }
        return multimediaRecords;

    }

    public static List<MultimediaDemand> findMultimediaDemands(String cardid, String stepid) {
        List<MultimediaDemand> multimediaDemands = new ArrayList<MultimediaDemand>();
        db = helper.getReadableDatabase();
        Cursor cursor = db.query("MultimediaDemand", null, "KEYCardCode=? and StepId=?", new String[]{String.valueOf(cardid), String.valueOf(stepid)}, null, null, "SequenceNumber", null);
        while (cursor.moveToNext()) {
            multimediaDemands.add(new MultimediaDemand(cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5),
                    cursor.getString(6), cursor.getString(7), cursor.getString(8), cursor.getString(9)));

        }
        return multimediaDemands;
    }

    public void insert(Object t, Context context) throws IllegalArgumentException, IllegalAccessException { // dbHelper = new DBOpenHelper(context);
        SQLiteDatabase db = null;
        try {
            db = helper.getWritableDatabase();
            Field[] fields = t.getClass().getDeclaredFields();
            ContentValues newValues = new ContentValues();
            for (int i = 0; i < fields.length; i++) {
                fields[i].setAccessible(true);//AccessibleTest类中的成员变量为private,故必须进行此操作
                Object valueString = fields[i].get(t);
                newValues.put(fields[i].getName(), valueString.toString());

            }
            String tableString = t.getClass().getSimpleName();
            //String tableString=String.valueOf(t);
            db.insert(tableString, null, newValues);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }


    }

    public void clearTable(String tablename) {
        // TODO Auto-generated method stub
        String sqlString = "delete from " + tablename;
        db.execSQL(sqlString);
    }

    public static void addMPI(WorkingProcedure wp, String sequencenumber) {
        // TODO Auto-generated method stub
        ContentValues contentValues = new ContentValues();
        contentValues.put("SystemId", DateManager.getDateSystemId());
        contentValues.put("StepId", wp.getSystemId());
        contentValues.put("CardCode", wp.getKEYCardCode());
        contentValues.put("SequenceNumber", String.valueOf(Integer.valueOf(sequencenumber) + 1));
        contentValues.put("KEYCardCode", wp.getKEYCardCode());
        contentValues.put("CreateDate", DateManager.getModifyDateString());
        contentValues.put("ParaCode", "0");
        contentValues.put("State", "1");
        db.insert("MostPortItem", null, contentValues);

    }

    public static void addMD(WorkingProcedure wp, String sequencenumber) {
        ContentValues cv = new ContentValues();
        cv.put("StepId", wp.getSystemId());
        String systemIdString = String.format("%s1", DateManager.getDateSystemId());
        cv.put("SystemId", systemIdString);
        cv.put("SequenceNumber", String.valueOf(Integer.valueOf(sequencenumber) + 1));
        cv.put("KEYCardCode", wp.getKEYCardCode());
        cv.put("MultimediaType", "1");
        cv.put("State", "1");
        ContentValues cv2 = new ContentValues();
        cv2.put("StepId", wp.getSystemId());
        cv2.put("SystemId", String.format("%s2", DateManager.getDateSystemId()));
        cv2.put("KEYCardCode", wp.getKEYCardCode());
        cv2.put("State", "1");
        cv2.put("RecordDate", DateManager.getModifyDateString());
        cv2.put("RecordingProductId", "0");
        cv2.put("MultimediaDemandId", wp.getSystemId());
        cv2.put("QcCardId", wp.getQcCardId());
        db.insert("MultimediaDemand", null, cv);
        db.insert("MultimediaRecord", null, cv2);


    }

    public static void addEI(WorkingProcedure wp, String sequencenumber) {
        ContentValues cv = new ContentValues();
        cv.put("StepId", wp.getSystemId());
        cv.put("SystemId", DateManager.getDateSystemId());
        cv.put("SequenceNumber", String.valueOf(Integer.valueOf(sequencenumber) + 1));
        cv.put("KEYCardCode", wp.getKEYCardCode());
        cv.put("QcCardCode", wp.getKEYCardCode());
        cv.put("DataType", "1");
        cv.put("Produce", wp.getProduce());
        cv.put("Category", wp.getStep());
        cv.put("Item", "0");
        cv.put("State", "1");
        cv.put("IsDemand", "1");
        cv.put("ExamineDemandId", String.format("%s%s", wp.getSystemId(), "1"));
        db.insert("ExamineItem", null, cv);

    }

    public static void deleteEi(ExamineItem ei) {
        db.delete("ExamineItem", "SystemId=? and StepId=? and KEYCardCode=?", new String[]{ei.getSystemId(), ei.getStepId(), ei.getKEYCardCode()});
    }

    public static void deleteMPi(MostPortItem mi) {
        db.delete("MostPortItem", "SystemId=? and StepId=? and KEYCardCode=?", new String[]{mi.getSystemId(), mi.getStepId(), mi.getKEYCardCode()});
    }

    public static void deleteMd(MultimediaDemand md, MultimediaRecord mr) {
        db.delete("MultimediaDemand", "SystemId=? and StepId=? and KEYCardCode=?", new String[]{md.getSystemId(), md.getStepId(), md.getKEYCardCode()});
        db.delete("MultimediaRecord", "SystemId=? and StepId=? and KEYCardCode=? and MultimediaDemandId=?", new String[]{mr.getSystemId(), mr.getStepId(), mr.getKEYCardCode(), mr.getMultimediaDemandId()
        });
    }

    public static void copyMPI(MostPortItem mpi, String SequnceNumber) {
        // TODO Auto-generated method stub
        MostPortItem mpiItem = new MostPortItem();
        try {
            mpiItem = (MostPortItem) mpi.clone();
        } catch (CloneNotSupportedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        mpiItem.setSystemId(DateManager.getDateSystemId());
        mpiItem.setOperator("");
        mpiItem.setReInnerChecker("");
        mpiItem.setChecker("");
        mpiItem.setStepId(mpi.getStepId());
        mpiItem.setSequenceNumber(String.valueOf(Integer.valueOf(SequnceNumber) + 1));
        insertData(mpiItem);

    }

    public static void copyEI(ExamineItem ei, String sequenceNumber) {
        ExamineItem eitem = new ExamineItem();
        try {
            eitem = (ExamineItem) ei.clone();
        } catch (CloneNotSupportedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        eitem.setSystemId(DateManager.getDateSystemId());
        eitem.setOperator("");
        eitem.setReInterChecker("");
        eitem.setChecker("");
        eitem.setSequenceNumber(String.valueOf(Integer.valueOf(sequenceNumber) + 1));
        insertData(eitem);

    }

    public static void copyMD(MultimediaDemand md, MultimediaRecord mr, String sequenceNumber) {
        MultimediaRecord mur = new MultimediaRecord();
        MultimediaDemand mud = new MultimediaDemand();
        try {
            mur = (MultimediaRecord) mr.clone();
        } catch (CloneNotSupportedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            mud = (MultimediaDemand) md.clone();
        } catch (CloneNotSupportedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        mur.setSystemId(String.format("0%s%d", DateManager.getDateSystemId(), 3));
        mur.setVerifier("");
        mur.setTechnic("");
        mur.setRecordDate("");
        mur.setRecordDate(DateManager.getModifyDateString());
        mur.setStepId(md.getStepId());
        mur.setMultimediaDemandId(String.format("0%s%d", DateManager.getDateSystemId(), 3));
        mud.setSystemId(String.format("0%s%d", DateManager.getDateSystemId(), 3));
        mud.setSequenceNumber(String.valueOf(Integer.valueOf(sequenceNumber) + 1));
        insertData(mud);
        insertData(mur);

    }

    public static void insertData(Object t) { // dbHelper = new DBOpenHelper(context);
        SQLiteDatabase db = null;
        try {
            db = helper.getWritableDatabase();
            Field[] fields = t.getClass().getDeclaredFields();
            ContentValues newValues = new ContentValues();
            for (int i = 0; i < fields.length; i++) {
                fields[i].setAccessible(true);//AccessibleTest类中的成员变量为private,故必须进行此操作
                Object valueString = fields[i].get(t);
                newValues.put(fields[i].getName(), valueString.toString());

            }
            String tableString = t.getClass().getSimpleName();
            //String tableString=String.valueOf(t);
            db.insert(tableString, null, newValues);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }


    }
}